<template>
  <div class="rule-management">
    <!-- 头部 -->
    <div class="header">
      <div class="header-left">
        <button class="back-btn" @click="goBack">
          <i class="fas fa-arrow-left"></i>
        </button>
        <h2>充值规则管理</h2>
      </div>
      <button class="add-btn" @click="handleAddRule">
        <i class="fas fa-plus"></i>
        新增规则
      </button>
    </div>

    <!-- 规则列表 -->
    <div class="rules-container">
      <div class="loading" v-if="loading">
        <i class="fas fa-spinner fa-spin"></i>
        <p>加载中...</p>
      </div>

      <div class="rules-list" v-else>
        <div v-if="rules.length === 0" class="empty-state">
          <i class="fas fa-inbox"></i>
          <p>暂无充值规则</p>
        </div>

        <div v-for="rule in rules" :key="rule.id" class="rule-card">
          <div class="rule-content">
            <div class="rule-header">
              <h3>规则 #{{ rule.id }}</h3>
              <span class="status-badge active">启用</span>
            </div>
            <div class="rule-details">
              <div class="detail-item">
                <span class="label">规则名称:</span>
                <span class="value">{{ rule.name }}</span>
              </div>
              <div class="detail-item">
                <span class="label">最小充值金额:</span>
                <span class="value">{{ rule.minAmount }} 元</span>
              </div>
              <div class="detail-item">
                <span class="label">奖励比例:</span>
                <span class="value">{{ rule.bonusRate }}%</span>
              </div>
              <div class="detail-item">
                <span class="label">奖励金额:</span>
                <span class="value">{{ rule.bonusAmount }} 元</span>
              </div>
              <div class="detail-item">
                <span class="label">优先级:</span>
                <span class="value">{{ rule.priority }}</span>
              </div>
            </div>
          </div>
          <div class="rule-actions">
            <button class="edit-btn" @click="editRule(rule)">
              <i class="fas fa-edit"></i>
              编辑
            </button>
            <button class="delete-btn" @click="deleteRule(rule.id)">
              <i class="fas fa-trash"></i>
              删除
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 新增/编辑规则对话框 -->
    <div class="dialog-overlay" v-if="showAddDialog || showEditDialog" @click.self="closeDialog">
      <div class="dialog" v-if="showAddDialog" @click.stop>
        <div class="dialog-header">
          <h3>新增充值规则</h3>
          <button class="close-btn" @click="closeDialog">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="dialog-body">
          <div class="form-group">
            <label>规则名称</label>
            <input type="text" v-model="formData.name" placeholder="请输入规则名称">
          </div>
          <div class="form-group">
            <label>最小充值金额 (元)</label>
            <input type="number" v-model="formData.minAmount" placeholder="请输入最小充值金额" step="0.01">
          </div>
          <div class="form-group">
            <label>奖励比例 (%)</label>
            <input type="number" v-model="formData.bonusRate" placeholder="请输入奖励比例" step="0.01">
          </div>
          <div class="form-group">
            <label>奖励金额 (元)</label>
            <input type="number" v-model="formData.bonusAmount" placeholder="请输入奖励金额" step="0.01">
          </div>
          <div class="form-group">
            <label>优先级</label>
            <input type="number" v-model="formData.priority" placeholder="请输入优先级 (数字越大优先级越高)">
          </div>
        </div>
        <div class="dialog-footer">
          <button class="cancel-btn" @click="closeDialog">取消</button>
          <button class="confirm-btn" @click="saveRule">确定</button>
        </div>
      </div>

      <div class="dialog" v-if="showEditDialog" @click.stop>
        <div class="dialog-header">
          <h3>编辑充值规则</h3>
          <button class="close-btn" @click="closeDialog">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="dialog-body">
          <div class="form-group">
            <label>规则名称</label>
            <input type="text" v-model="formData.name" placeholder="请输入规则名称">
          </div>
          <div class="form-group">
            <label>最小充值金额 (元)</label>
            <input type="number" v-model="formData.minAmount" placeholder="请输入最小充值金额" step="0.01">
          </div>
          <div class="form-group">
            <label>奖励比例 (%)</label>
            <input type="number" v-model="formData.bonusRate" placeholder="请输入奖励比例" step="0.01">
          </div>
          <div class="form-group">
            <label>奖励金额 (元)</label>
            <input type="number" v-model="formData.bonusAmount" placeholder="请输入奖励金额" step="0.01">
          </div>
          <div class="form-group">
            <label>优先级</label>
            <input type="number" v-model="formData.priority" placeholder="请输入优先级 (数字越大优先级越高)">
          </div>
        </div>
        <div class="dialog-footer">
          <button class="cancel-btn" @click="closeDialog">取消</button>
          <button class="confirm-btn" @click="updateRule">确定</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { rulesAPI } from '@/api/rules.js'

const router = useRouter()

const rules = ref([])
const loading = ref(false)
const showAddDialog = ref(false)
const showEditDialog = ref(false)
const editingId = ref(null)

const formData = ref({
  name: '',
  minAmount: 0,
  bonusRate: 0,
  bonusAmount: 0,
  priority: 0
})

// 加载规则列表
const loadRules = async () => {
  loading.value = true
  try {
    const response = await rulesAPI.recharge.getAll()
    console.log('充值规则响应:', response)
    if (response.data && response.data.success && response.data.data) {
      rules.value = response.data.data
    } else {
      rules.value = []
    }
  } catch (error) {
    console.error('获取充值规则失败:', error)
    alert('获取规则列表失败，请重试')
  } finally {
    loading.value = false
  }
}

// 新增规则按钮点击
const handleAddRule = () => {
  formData.value = {
    name: '',
    minAmount: 0,
    bonusRate: 0,
    bonusAmount: 0,
    priority: 0
  }
  showAddDialog.value = true
}

// 新增规则
const saveRule = async () => {
  if (!validateForm()) return

  try {
    const response = await rulesAPI.recharge.create(formData.value)
    if (response.data && response.data.success !== false) {
      alert('添加成功！')
      closeDialog()
      await loadRules()
    }
  } catch (error) {
    console.error('添加规则失败:', error)
    alert('添加失败，请重试')
  }
}

// 编辑规则
const editRule = (rule) => {
  editingId.value = rule.id
  formData.value = {
    name: rule.name,
    minAmount: rule.minAmount,
    bonusRate: rule.bonusRate,
    bonusAmount: rule.bonusAmount,
    priority: rule.priority
  }
  showEditDialog.value = true
}

// 更新规则
const updateRule = async () => {
  if (!validateForm()) return

  try {
    const response = await rulesAPI.recharge.update(editingId.value, formData.value)
    if (response.data && response.data.success !== false) {
      alert('更新成功！')
      closeDialog()
      await loadRules()
    }
  } catch (error) {
    console.error('更新规则失败:', error)
    alert('更新失败，请重试')
  }
}

// 删除规则
const deleteRule = async (id) => {
  if (!confirm('确定要删除这条规则吗？')) return

  try {
    const response = await rulesAPI.recharge.delete(id)
    if (response.data && response.data.success !== false) {
      alert('删除成功！')
      await loadRules()
    }
  } catch (error) {
    console.error('删除规则失败:', error)
    alert('删除失败，请重试')
  }
}

// 表单验证
const validateForm = () => {
  if (!formData.value.name || formData.value.name.trim() === '') {
    alert('规则名称不能为空')
    return false
  }
  if (formData.value.minAmount < 0) {
    alert('最小充值金额不能为负数')
    return false
  }
  if (formData.value.bonusRate < 0) {
    alert('奖励比例不能为负数')
    return false
  }
  if (formData.value.bonusAmount < 0) {
    alert('奖励金额不能为负数')
    return false
  }
  return true
}

// 关闭对话框
const closeDialog = () => {
  showAddDialog.value = false
  showEditDialog.value = false
  editingId.value = null
  formData.value = {
    name: '',
    minAmount: 0,
    bonusRate: 0,
    bonusAmount: 0,
    priority: 0
  }
}

// 返回
const goBack = () => {
  router.push('/admin/dashboard')
}

onMounted(() => {
  loadRules()
})
</script>

<style scoped>
.rule-management {
  min-height: 100vh;
  background-color: #f8f9fa;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.back-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #666;
  padding: 5px;
  border-radius: 5px;
  transition: background 0.3s;
}

.back-btn:hover {
  background: #f0f0f0;
}

.header h2 {
  margin: 0;
  color: #333;
  font-size: 24px;
}

.add-btn {
  background: #ee5a24;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  transition: background 0.3s;
}

.add-btn:hover {
  background: #ff6b35;
}

.rules-container {
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  padding: 20px;
  min-height: 400px;
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400px;
  color: #999;
}

.loading i {
  font-size: 48px;
  margin-bottom: 10px;
  color: #ee5a24;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400px;
  color: #999;
}

.empty-state i {
  font-size: 64px;
  margin-bottom: 15px;
  color: #ccc;
}

.rules-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.rule-card {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  transition: box-shadow 0.3s;
}

.rule-card:hover {
  box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

.rule-content {
  flex: 1;
}

.rule-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
}

.rule-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
}

.status-badge {
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.active {
  background: #d4edda;
  color: #155724;
}

.rule-details {
  display: grid;
  grid-template-columns: repeat(2, minmax(200px, 1fr));
  gap: 10px;
}

.detail-item {
  display: flex;
  gap: 8px;
}

.detail-item .label {
  color: #666;
  font-size: 14px;
}

.detail-item .value {
  color: #333;
  font-weight: 500;
  font-size: 14px;
}

.rule-actions {
  display: flex;
  gap: 10px;
}

.edit-btn, .delete-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  transition: all 0.3s;
}

.edit-btn {
  background: #007bff;
  color: white;
}

.edit-btn:hover {
  background: #0056b3;
}

.delete-btn {
  background: #dc3545;
  color: white;
}

.delete-btn:hover {
  background: #c82333;
}

/* 对话框样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: auto;
  padding: 20px;
}

.dialog {
  background: #ffffff;
  border-radius: 10px;
  width: 100%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
  z-index: 10000;
  box-shadow: 0 10px 40px rgba(0,0,0,0.3);
  animation: dialogFadeIn 0.3s ease-out;
  position: relative;
}

@keyframes dialogFadeIn {
  from {
    opacity: 0;
    transform: scale(0.9) translateY(-20px);
  }
  to {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e0e0e0;
}

.dialog-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #999;
}

.dialog-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  color: #333;
  font-weight: 500;
  font-size: 14px;
}

.form-group input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 14px;
  box-sizing: border-box;
}

.form-group input:focus {
  outline: none;
  border-color: #ee5a24;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 20px;
  border-top: 1px solid #e0e0e0;
}

.cancel-btn, .confirm-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.3s;
}

.cancel-btn {
  background: #f0f0f0;
  color: #333;
}

.cancel-btn:hover {
  background: #e0e0e0;
}

.confirm-btn {
  background: #ee5a24;
  color: white;
}

.confirm-btn:hover {
  background: #ff6b35;
}

@media (max-width: 768px) {
  .rule-details {
    grid-template-columns: 1fr;
  }

  .rule-card {
    flex-direction: column;
  }

  .rule-actions {
    width: 100%;
    margin-top: 15px;
  }
}
</style>
